import { utils, writeFileXLSX } from "xlsx";
import { Md5 } from "ts-md5";
import { ENUM_TON_NOTCH, ExtSkuTpl, NotchAble, Stockable, TonTpl, WithStockTotal } from "qqlx-core";

import { toNumber, doBigIntSort, isStringNotValid } from "@lib/com.verify";
import { getTime, getRangeMonth } from "@lib/com.time";
import { TonTplSchema } from "@/river/ton-tpl";

/** 根据名称/规格/单位/标签字符串，生成唯一库存标识 */
export function getTplIvId(tpl: ExtSkuTpl, labelStr: string) {
  const { name, norm, unit } = tpl;
  if (isStringNotValid(name)) throw new Error(`缺少商品名称`);
  else if (isStringNotValid(norm)) throw new Error(`缺少商品规格`);

  const md5 = new Md5();
  md5.appendStr([name, norm, unit, labelStr].filter((e) => !!e).join("；"));
  return md5.end() as string;
}

/** 把-N-个库存汇总成-n-个库存 */
export function doNotchMerge(ls: NotchAble[]) {
  const notchMap = new Map<ENUM_TON_NOTCH, Omit<NotchAble, "key">>();

  for (const { type, total } of ls) {
    const matchNotch = notchMap.get(type);
    if (matchNotch) {
      const { max } = doBigIntSort(BigInt(matchNotch.total), [BigInt(total)]);
      matchNotch.total = max.toString();
    } else {
      notchMap.set(type, { type, total });
    }
  }
  return { map: notchMap };
}

/** 帮助商品模板，补充库存信息 */
export function formatTonTplNotch<T>(tplLs: (T & TonTpl)[], remoteNotchs: (Stockable & NotchAble)[]): (T & TonTpl & WithStockTotal)[] {
  return tplLs.map((tpl) => {
    const counts = (remoteNotchs || []).filter((c) => c.key === "count" && c.ivid === tpl.ivid);
    const { map } = doNotchMerge(counts);
    const total: WithStockTotal = {
      stockCounts: counts.length,
      stockTons: 0,
      //
      withInOutCountTotal: map.get(ENUM_TON_NOTCH.IN_OUT)?.total || "0",
      withInOutTonTotal: "0",
      //
      withNotInCountTotal: map.get(ENUM_TON_NOTCH.NOT_IN)?.total || "0",
      withNotInTonTotal: "0",
      //
      withNotProcessCountTotal: map.get(ENUM_TON_NOTCH.NOT_PROCESS)?.total || "0",
      withNotProcessTonTotal: "0",
      //
      withNotOutCountTotal: map.get(ENUM_TON_NOTCH.NOT_OUT)?.total || "0",
      withNotOutTonTotal: "0",
    };

    return { ...tpl, ...total };
  });
}

/** 快速添加冷轧板 */
export function getSkuTpls001() {
  const list = [];
  for (const n of ["有花镀锌小板", "无花镀锌小板", "冷轧小板", "酸洗小板"]) {
    for (const h of ["0.3", "0.5", "0.7", "1.0", "1.1", "1.2", "1.3", "1.4", "1.5", "2.0"]) {
      list.push({ name: n, norm: h + "*1000*2000" });
    }
  }
  for (const n of ["有花镀锌板", "无花镀锌板", "冷轧板", "酸洗板"]) {
    for (const h of ["0.3", "0.5", "0.7", "1.0", "1.1", "1.2", "1.3", "1.4", "1.5", "2.0"]) {
      list.push({ name: n, norm: h + "*1250*2500" });
    }
  }
  for (const n of ["有花镀锌大板", "无花镀锌大板", "冷轧大板", "酸洗大板"]) {
    for (const h of ["0.3", "0.5", "0.7", "1.0", "1.1", "1.2", "1.3", "1.4", "1.5", "2.0"]) {
      list.push({ name: n, norm: h + "*1500*3000" });
    }
  }
  return list.map((s) => ({ ...new TonTplSchema(), ...s, unit: "张" }));
}

/** 快速添加冷轧卷 */
export function getSkuTpls002() {
  const list = [];
  for (const n of ["有花镀锌", "无花镀锌", "冷轧", "酸洗"]) {
    for (const h of ["0.3", "0.5", "0.7", "1.0", "1.1", "1.2", "1.3", "1.4", "1.5", "2.0"]) {
      list.push({ name: n, norm: h + "*1000*C" });
    }
  }
  for (const n of ["有花镀锌", "无花镀锌", "冷轧", "酸洗"]) {
    for (const h of ["0.3", "0.5", "0.7", "1.0", "1.1", "1.2", "1.3", "1.4", "1.5", "2.0"]) {
      list.push({ name: n, norm: h + "*1250*C" });
    }
  }
  for (const n of ["有花镀锌", "无花镀锌", "冷轧", "酸洗"]) {
    for (const h of ["0.3", "0.5", "0.7", "1.0", "1.1", "1.2", "1.3", "1.4", "1.5", "2.0"]) {
      list.push({ name: n, norm: h + "*1500*C" });
    }
  }
  return list.map((s) => ({ ...new TonTplSchema(), ...s, unit: "个" }));
}

/** Excel模版文件：商品/联系人/资金发票 */
export function downloadFileTpl() {
  const dayStr = getTime(toNumber(getRangeMonth().startTime)).text;
  const workbook = utils.book_new();

  const Sheet0 = utils.aoa_to_sheet([
    ["@标签", "@品名", "@规格", "@重量/吨", "@数量", "@单位", "@单价/元", "@备注", "@日期", "请勿更改@标题头部"],
    ["马钢;ZP700", "有花板卷", "1.0*1250*C", "13.78", "1", "个", "4500", "", dayStr],
    ["马钢;ZP700", "有花板卷", "1.5*1250*C", "15.45", "1", "个", "4500", "", dayStr],
    ["鞍钢;DC51D+Z", "热镀锌板卷", "1.0*1250*C", "6.8", "1", "个", "4200", "", dayStr],
    ["鞍钢;DC51D+Z", "热镀锌板卷", "1.5*1250*C", "16.18", "1", "个", "4200", "", dayStr],
    ["宝钢;ZP100", "无花板卷", "1.0*1250*C", "14.78", "1", "个", "4100", "", dayStr],
    ["宝钢;ZP100", "无花板卷", "1.5*1250*C", "19.45", "1", "个", "4100", "", dayStr],
  ]);
  utils.book_append_sheet(workbook, Sheet0, "商品导入");

  const Sheet1 = utils.aoa_to_sheet([
    ["@联系人名称", "@拼音简称", "@备注", "请勿更改@标题头部"],
    ["清泉流响软件信息有限公司", "qqlx", "13046661300（微信）"],
    ["宝山钢铁股份有限公司", "bsgt", "02126647000"],
    ["广东中南钢铁股份有限公司", "zngt", "07518788929"],
    ["马鞍山钢铁股份有限公司", "masgt", "2877326"],
    ["太原钢铁（集团）有限公司", "tygt", "03512137728"],
    ["宝钢集团新疆八一钢铁有限公司", "bygt", "09913890166"],
  ]);
  utils.book_append_sheet(workbook, Sheet1, "联系人导入");

  const Sheet2 = utils.aoa_to_sheet([
    ["@对方公司", "@我方抬头", "@银行", "@日期", "@金额", "@备注", "@编号", "请勿更改@标题头部"],
    ["宝山钢铁股份有限公司", "东方钢材贸易公司", "中国银行", dayStr, "45000", "", ""],
    ["广东中南钢铁股份有限公司", "东方钢材贸易公司", "农业银行", dayStr, "126000", "", ""],
    ["马鞍山钢铁股份有限公司", "东方钢材贸易公司", "工商银行", dayStr, "87000", "", ""],
    ["太原钢铁（集团）有限公司", "东方钢材贸易公司", "建设银行", dayStr, "336500", "", ""],
    ["宝钢集团新疆八一钢铁有限公司", "东方钢材贸易公司", "招商银行", dayStr, "160000", "", ""],
  ]);
  utils.book_append_sheet(workbook, Sheet2, "资金导入");

  const Sheet3 = utils.aoa_to_sheet([
    ["@对方公司", "@我方抬头", "@发票号码", "@日期", "@金额", "@税额", "@备注", "@编号", "请勿更改@标题头部"],
    ["宝山钢铁股份有限公司", "东方钢材贸易公司", "11110000", dayStr, "45000", 4500 * 0.13, "", ""],
    ["广东中南钢铁股份有限公司", "东方钢材贸易公司", "12110000", dayStr, "126000", 126000 * 0.13, "", ""],
    ["马鞍山钢铁股份有限公司", "东方钢材贸易公司", "13110000", dayStr, "87000", 87000 * 0.13, "", ""],
    ["太原钢铁（集团）有限公司", "东方钢材贸易公司", "16110000", dayStr, "336500", 336500 * 0.13, "", ""],
    ["宝钢集团新疆八一钢铁有限公司", "东方钢材贸易公司", "18110000", dayStr, "160000", 160000 * 0.13, "", ""],
  ]);
  utils.book_append_sheet(workbook, Sheet3, "发票导入");

  writeFileXLSX(workbook, "清泉流响-批量导入模板.xlsx");
}
